package com.yuyang.wifi.activitys.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.NewMainHomeActivity;
import com.yuyang.wifi.activitys.web.WebViewSecretActivity;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.utils.AppUtils;
import com.yuyang.wifi.utils.ButtonLimitClickUtils;
import com.yuyang.wifi.utils.ClipboardUtils;
import com.yuyang.wifi.utils.DeviceInfoUtils;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.MaterialDialogHelper;
import com.yuyang.wifi.utils.NetworkUtils;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.views.XTextView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class WeChatLoginActivity extends BaseActivity {


    private RecyclerView mRecyclerView;
    private String openid;
    private String unionid;
    private String name;
    @BindView(R.id.show_version_code)
    View showVersionCode;
    @BindView(R.id.tv_wechat_login)
    TextView tvWechatLogin;
    @BindView(R.id.iv_xy_btn)
    ImageView ivXyBtn;
    @BindView(R.id.xt_login_send)
    XTextView xtLoginSend;
    @BindView(R.id.rl_login_send)
    RelativeLayout rlLoginSend;
    private String emei;
    private String mNetType;
    private boolean isUnSelect = false;

    @Override
    protected void initActionBar() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_we_chat_login;
    }

    @Override
    protected void initContentView() {
        String agreeProtocol = SpUtil.find(AppConstant.KEY_AGREE_PROTOCOL);
        if (!TextUtils.isEmpty(agreeProtocol)) {
            requestCameraPermission();
        } else {
        }

        showVersionCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                String appName = DeviceInfoUtils.getAppName(WeChatLoginActivity.this);
                String verName = DeviceInfoUtils.getVerName(WeChatLoginActivity.this);
                int localVersionCode = DeviceInfoUtils.getLocalVersionCode(WeChatLoginActivity.this);
                String channelName = DeviceInfoUtils.getUmChannelName(WeChatLoginActivity.this);
                String versionCodeNum = DeviceInfoUtils.getVersionCodeNum();
                String phoneBrand = DeviceInfoUtils.getDeviceBrand();
                String phoneSystemModel = DeviceInfoUtils.getSystemModel();
                String userId = SpUtil.find(AppConstant.KEY_USER_ID);
                String userName = SpUtil.find(AppConstant.KEY_USER_NAME);

                ClipboardUtils.copyText(WeChatLoginActivity.this, "App====" + appName + "\n" + "版本====" +
                        verName + "\n" + "版本code====" + localVersionCode + "\n" + "渠道号====" +
                        channelName + "\n" + "userId====" + userId + "\n" + "userName====" + userName +
                        "\n" + "IMEI====" + emei + "\n" + "手机品牌型号====" + phoneBrand + " " + phoneSystemModel + "\n" + "版本kkkcode====" + versionCodeNum);
                ToastUtils.showLongToast(WeChatLoginActivity.this, "已复制");

                return false;
            }
        });

        SpUtil.saveOrUpdate(AppConstant.KEY_CHANNEL, DeviceInfoUtils.getUmChannelName(WeChatLoginActivity.this));
    }

    //请求相机权限
    private void requestCameraPermission() {
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_CAMERA,
                new String[]{Manifest.permission.READ_PHONE_STATE}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        emei = getEmei(WeChatLoginActivity.this);
                        SpUtil.saveOrUpdate(AppConstant.KEY_IMEI, emei);
                    }

                    @Override
                    public void onPermissionDenied() {
                        ToastUtils.showShortToast(WeChatLoginActivity.this, "当前权限务必开启,否则影响试玩,请重新进入授权");
                        //ActivityManager.getInstance().finishAllActivity();
                        MPermissionUtils.showRemindDialog(WeChatLoginActivity.this, getFragmentManager());
                    }
                });
    }

    private void requestDeviceIdCameraPermission() {
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_CAMERA,
                new String[]{Manifest.permission.READ_PHONE_STATE}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        emei = getEmei(WeChatLoginActivity.this);
                        SpUtil.saveOrUpdate(AppConstant.KEY_IMEI, emei);
                        //进入功能页
                        String token = SpUtil.find(AppConstant.KEY_TOKEN);
                        if (TextUtils.isEmpty(token)) {
                            loginBtnClick();
                        } else {
                            startActivity(new Intent(WeChatLoginActivity.this, NewMainHomeActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onPermissionDenied() {
                        ToastUtils.showShortToast(WeChatLoginActivity.this, "当前权限务必开启,否则影响试玩,请重新进入授权");
                        //ActivityManager.getInstance().finishAllActivity();
                        MPermissionUtils.showRemindDialog(WeChatLoginActivity.this, getFragmentManager());
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnClick({R.id.tv_wechat_login, R.id.tv_connect_service, R.id.tv_user_protocol,
            R.id.tv_privacy_protocol, R.id.rl_xy_btn, R.id.left_icon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_icon:
                finish();
                break;
            case R.id.rl_xy_btn:
                if (isUnSelect) {
                    isUnSelect = false;
                    ivXyBtn.setBackgroundResource(R.mipmap.icon_small_un_select_circle);
                } else {
                    ivXyBtn.setBackgroundResource(R.mipmap.icon_small_select_circle);
                    isUnSelect = true;
                }
                break;
            case R.id.tv_wechat_login:
                if (isUnSelect) {
                    ButtonLimitClickUtils.setLimitClick(tvWechatLogin);
                    MyApplication.logEvent(WeChatLoginActivity.this, "登录.点击微信登录");
                    requestDeviceIdCameraPermission();
                } else {
                    ToastUtils.showShortToast(WeChatLoginActivity.this, "请勾选当前协议");
                    return;
                }
                break;
//            case R.id.tv_wechat_login:
//                ButtonLimitClickUtils.setLimitClick(tvWechatLogin);
//                MyApplication.logEvent(WeChatLoginActivity.this, "登录.点击微信登录");
//                //进入功能页
//                String token = SpUtil.find(AppConstant.KEY_TOKEN);
//                if (TextUtils.isEmpty(token)) {
//                    loginBtnClick();
//                } else {
//                    startActivity(new Intent(WeChatLoginActivity.this, NewMainHomeActivity.class));
//                    finish();
//                }
//                break;
            case R.id.tv_connect_service:
                MyApplication.logEvent(WeChatLoginActivity.this, "登录.点击联系客服");
                break;
            case R.id.tv_user_protocol://注册协议
                MyApplication.logEvent(WeChatLoginActivity.this, "登录.点击用户协议");
                Intent intent = new Intent(WeChatLoginActivity.this, WebViewSecretActivity.class);
                intent.putExtra("url", "file:///android_asset/index2.html");
                intent.putExtra("title", "用户注册协议");
                startActivity(intent);
                break;
            case R.id.tv_privacy_protocol://隐私协议
                MyApplication.logEvent(WeChatLoginActivity.this, "登录.点击隐私协议");
                Intent intent2 = new Intent(WeChatLoginActivity.this, WebViewSecretActivity.class);
                intent2.putExtra("url", "file:///android_asset/index.html");
                intent2.putExtra("title", "用户隐私协议");
                startActivity(intent2);
                break;
        }
    }

    //微信登录按钮点击
    private void loginBtnClick() {
        if (!AppUtils.isInstallApp(WeChatLoginActivity.this, AppConstant.PACKAGE_WEIXIN)) {
            MaterialDialogHelper.getNormalMaterialDialog(WeChatLoginActivity.this)
                    .content("请先安装手机微信").positiveText("去下载微信")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse("http://weixin.qq.com");
                            intent.setData(content_url);
                            startActivity(intent);
                        }
                    }).show();
            return;
        }
        wakenWeChat();//微信授权
        // shareUrl(SHARE_MEDIA.WEIXIN);
    }

    //分享  调起分享sdk代码
//    public void shareUrl(SHARE_MEDIA plat) {
//        UMWeb web = new UMWeb("https://www.baidu.com/");
//        web.setTitle("fjkdlfkjdskjfldkjflkjsdlkjfdkjf");
//        web.setThumb(new UMImage(this, R.mipmap.app_launch_icon));
//        web.setDescription("dkfldkfldklfkdlkfldkfldkfldkfdfdfdfdfagrgreger");
//        new ShareAction(WeChatLoginActivity.this).withMedia(web)
//                .setPlatform(plat)
//                .setCallback(shareListener).share();
//    }

    //分享回调
    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.showShortToast(WeChatLoginActivity.this, "分享回调成功");
            //更新微信调用次数
            //upWechatCount();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(WeChatLoginActivity.this, "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(WeChatLoginActivity.this, "取消了", Toast.LENGTH_LONG).show();

        }
    };

    private void wakenWeChat() {
        // showLoadingDialog();
        boolean wifiConnected = NetworkUtils.isWifiConnected(WeChatLoginActivity.this);
        if (wifiConnected) {
            mNetType = "wifi";
        } else {
            mNetType = "mobile";
        }
        MyApplication.getInstance().getUmShareAPI().getPlatformInfo(WeChatLoginActivity.this,
                SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                        openid = map.get("openid");
                        unionid = map.get("unionid");
                        String iconurl = map.get("iconurl");
                        name = map.get("name");
                        // ToastUtils.showShortToast(WeChatLoginActivity.this, name);
                        String accessToken = map.get("access_token");
                        Log.e("onComplete", "==1====" + openid);
                        Log.e("onComplete", "==2====" + unionid);
                        Log.e("onComplete", "======" + iconurl);
                        Log.e("onComplete", "======" + name);
                        //getUserInfo();
                        register(openid, unionid, name, iconurl);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        ToastUtils.showShortToast(getApplicationContext(), "登录失败");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        dismissDialog();
                    }
                });
    }

    //其中123是requestcode，可以根据这个code判断，用户是否同意了授权。如果没有同意，可以根据回调进行相应处理：
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
//        ToastUtils.showShortToast(WeChatLoginActivity.this, requestCode + "");
//    }

    private void register(final String openId, final String unionId, final String nickName, final String headUrl) {

    }


    public static String getEmei(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            return getAndroidId(context);
        } else {
            return getDeviceIds(context);
        }
    }

    private static String getAndroidId(Context context) {
        String deviceID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(deviceID)) {
            return deviceID;
        }
        return deviceID;
    }

    //获取设备ID
    public static String getDeviceIds(Context context) {

        try {
            TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyMgr != null) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return "";
                }
                String deviceId = telephonyMgr.getDeviceId();
                //Log.e("channel", "onViewClicked:" + deviceId);
                return deviceId;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

    @Override
    protected void onResume() {
        super.onResume();
        int localVersionCode = DeviceInfoUtils.getLocalVersionCode(MyApplication.getInstance());
        SpUtil.saveOrUpdate(AppConstant.KEY_VERSION_CODE, String.valueOf(localVersionCode));
        MyApplication.logEvent(WeChatLoginActivity.this, "登录");
    }

}
